// Copyright 2023 The titan Authors. All rights reserved.

// Project: titan
// IDE: GoLand
// Author: fucaihe@outlook.com
// File: news_index.go
// Date: 2023/12/26 12:50:55
// Description: 新闻数据业务逻辑的实现

package service

import (
	"context"
	"fmt"
	"strings"
	"time"

	"github.com/redis/go-redis/v9"

	"titan/pkg/md5"
)

type NewsIndexService interface {
	CheckDuplicate(ctx context.Context, link string) (bool, error)
	Insert(ctx context.Context, link string) (bool, error)
}

type newsIndexService struct {
	*Service
	Cache *redis.Client
}

func NewNewsIndexService(service *Service, cache *redis.Client) NewsIndexService {
	return &newsIndexService{
		Service: service,
		Cache:   cache,
	}
}

// NewsIndexCacheKeyPre 数据索引key前缀
const NewsIndexCacheKeyPre = "news_index_"

// CheckDuplicate 检查数据是否重复, true: 存在, false: 不存在
func (n *newsIndexService) CheckDuplicate(ctx context.Context, link string) (bool, error) {
	link = strings.TrimPrefix(link, "https")
	link = strings.TrimPrefix(link, "http")
	link = strings.TrimPrefix(link, ":")
	link = strings.TrimPrefix(link, "/")
	link = strings.TrimPrefix(link, "/")

	noProtocolId := md5.MD5(link)

	now := time.Now()
	lastYear := now.AddDate(-1, 0, 0)

	// 检查是否存在, 检查今年的
	exists, err := n.Cache.HExists(ctx, NewsIndexCacheKeyPre+now.Format("2006"), noProtocolId).Result()
	if err != nil {
		return false, err
	}

	// 如果不存在, 则检查去年的
	if !exists {
		exists, err = n.Cache.HExists(ctx, NewsIndexCacheKeyPre+lastYear.Format("2006"), noProtocolId).Result()
		if err != nil {
			return false, err
		}
	}

	return exists, nil
}

// Insert 插入索引, true: 成功, false: 失败
func (n *newsIndexService) Insert(ctx context.Context, link string) (bool, error) {
	link = strings.TrimPrefix(link, "https")
	link = strings.TrimPrefix(link, "http")
	link = strings.TrimPrefix(link, ":")
	link = strings.TrimPrefix(link, "/")
	link = strings.TrimPrefix(link, "/")

	noProtocolId := md5.MD5(link)

	now := time.Now()

	rst, err := n.Cache.HSet(ctx, NewsIndexCacheKeyPre+now.Format("2006"), noProtocolId).Result()
	if err != nil {
		return false, err
	}
	fmt.Println("ssfsfss --> ", rst)

	return false, err
}
